package boc.sx.gateway.core;

import boc.sx.gateway.service.BusinessHandler;
import boc.sx.gateway.socket.client.support.InitializerFactory;
import boc.sx.gateway.socket.client.NettyClient;
import boc.sx.gateway.util.ApplicationContextUtil;
import io.netty.channel.ChannelInitializer;
import org.apache.commons.lang3.StringUtils;

/*
 * @author zmx
 * @date 2022/8/10 15:38
 */

public class RequestRoute{


    public static Object sendMessageToTargetServer(Object msg,String serviceCode) throws InterruptedException {
        // 1.获取服务地址
        ServiceNode serviceNode = ServiceUrlLoader.findServiceNode(serviceCode);
        if(serviceNode==null){
            return null;
        }
        String s ="";
        // 2.负载均衡-挑选实际请求地址
        if(serviceNode.getUri().length>1){
            TransferHandler transferHandler = (TransferHandler) ApplicationContextUtil.applicationContext.getBean("transferHandler");
            s = transferHandler.voteOne(serviceNode);
        }else {
            s = serviceNode.getUri()[0];
        }
        //
        String[] split = s.split(":");
        String ip = split[0];
        int port = StringUtils.isNumeric(split[1]) ? Integer.parseInt(split[1]) : 8080 ;
        //3. 启动一个客户端连接目标。发送数据，获取数据(连接缓存，一定时间后断开连接)
        NettyClient nettyClient = (NettyClient) ApplicationContextUtil.applicationContext.getBean("nettyClient");
        String requestCode = ip+port+serviceNode.getPath()+"-"+msg.hashCode();
        ChannelInitializer http = InitializerFactory.getInitializer(serviceNode.getProtocol(), requestCode, msg, serviceNode.getPath());
        nettyClient.config(ip,port,requestCode);
        nettyClient.setClientProtocol(http);
        Object receive =nettyClient.run();
        //4. 收到后数据业务处理
        Object call = BusinessHandler.call(serviceCode, receive);
        //5. 返回数据
        return call;
    }


}
